package com.jushu.storbox.manager;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ReceiverConstent;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IShareINodeDao;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.ShareINode;
import com.jushu.storbox.newservice.IShareService;
import com.jushu.storbox.newservice.RemoteShareService;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.ShareResourceV2;

public class ShareScanManager {
	
	private final static String TAG = "ShareScanManager";
	
	private final static int STOP_SCAN_SHARE = 0x0010;
	private final static int START_SCAN_SHARE = 0x0011;
	private final static int COMPIRE_SCAN_RESULT = 0x0022;
	private final static int HAVA_NEW_SHARE = 0x0023;
	private final static int HAVA_NO_NEW_SHARE = 0x0024;

	private final static int RESULT_ERROR_INDEX = 0;
	private final static int RESULT_NOT_FINISHED = 1;
	private final static int RESULT_GET_FINISHED = 2;

	private final static int SCAN_LIFT_CYCLE = 2 * 60 * 1000;
	
	private final static int SHARE_PAGE_SIZE = 1000;
	
	private Context context = null;
	private boolean scanTaskStoped = false;
	private static ShareScanManager shareScanManager = null;
	
	private IShareService service = null;
	private IShareINodeDao shareDao = null;
	private CatchManager catchManager = null;
	
	private List<INodeShareV2> list = new ArrayList<INodeShareV2>();
	
	private ShareScanManager() {
	}
	
	public static ShareScanManager getInstance() {
		if(shareScanManager == null) {
			shareScanManager = new ShareScanManager();
		}
		return shareScanManager;
	}
	
	public void init(Context context) {
		this.context = context;
	}
	
	protected Context getContext() {
		if(context == null) {
			context = ShareDriveApplication.getInstance();
		}
		return context;
	}
	
	public void startScanShare() {
		LogUtil.i(TAG, "startScanShare....");
		scanTaskStoped = false;
		handler.sendEmptyMessage(START_SCAN_SHARE);
	}
	
	public void stopScanShare() {
		LogUtil.i(TAG, "stopScanShare....");
		scanTaskStoped = true;
		handler.sendEmptyMessage(STOP_SCAN_SHARE);
	}
	
	private IShareService getShareService() {
		if(service == null) {
			service = new RemoteShareService();
		}
		return service;
	}
	
	private IShareINodeDao getShareDao() {
		if(shareDao == null) {
			shareDao = DAOFactory.instance(getContext()).getShareINodeDao();
		}
		return shareDao;
	}
	
	private CatchManager getCatchManager() {
		if(catchManager == null) {
			catchManager = CatchManager.getInstance();
		}
		return catchManager;
	}
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case STOP_SCAN_SHARE:
				handler.removeCallbacks(scanTask);
				break;
				
			case START_SCAN_SHARE:
				handler.post(scanTask);
				break;
				
			case HAVA_NEW_SHARE:
				sendNewShareShip();
				break;
				
			case HAVA_NO_NEW_SHARE:
				sendNoNewShareShip();
				break;
				
			case COMPIRE_SCAN_RESULT:
				compaireScanResult();
				break;
				
			default:
				super.handleMessage(msg);
			}
		}

		private void sendNoNewShareShip() {
			final Context context = getContext();
			if(context != null) {
				Intent newShareShip = new Intent();
				newShareShip.setAction(ReceiverConstent.NO_NEW_SHARE_SHIP_FIND);
				context.sendBroadcast(newShareShip);
			}
		}

		private void sendNewShareShip() {
			final Context context = getContext();
			if(context != null) {
				Intent newShareShip = new Intent();
				newShareShip.setAction(ReceiverConstent.NEW_SHARE_SHIP_FIND);
				context.sendBroadcast(newShareShip);
			}
		}

		private void compaireScanResult() {
			int compaireResult = HAVA_NO_NEW_SHARE;
			LogUtil.d(TAG, "begin compaireScanResult...");

			//remove local dirty data
			boolean isDirtyItem = false;
			List<FileFolderInfo> dlist = getShareDao().getAllMySharedShip();
			for (FileFolderInfo localItem : dlist) {
				isDirtyItem = true;
                for (INodeShareV2 serverItem : list) {
                	if(localItem.getId().equals(serverItem.getNodeId().toString())
                		&& localItem.getOwnerBy().equals(serverItem.getOwnerId().toString())) {
                		isDirtyItem = false;
                		break;
                	}
                }
                //server cancel share
                if(isDirtyItem) {
                	getShareDao().deleteFolderOrFile(localItem.getId(), localItem.getOwnerBy());
                	
                	INodeShareV2 deleteItem = new INodeShareV2();
                	deleteItem.setNodeId(Long.valueOf(localItem.getId()));
                	deleteItem.setOwnerId(Long.valueOf(localItem.getOwnerBy()));
                	getCatchManager().removeShareINode(deleteItem);
                }
	        }
			
			//attach to local
			synchronized (list) {
				for(INodeShareV2 data : list) {
					ShareINode inode = getCatchManager().getShareINode(data);
					if(inode == null) {
						compaireResult = HAVA_NEW_SHARE;
						LogUtil.d(TAG, "hava new items been shared!");
						
						inode = new ShareINode();
						inode.valueOf(data);
						getShareDao().insertFolderOrFile(inode);
						
						getCatchManager().putShareINode(data, inode);
					} else {
						if(inode.getItemViewed() == IShareINodeDao.ITEM_NOT_VIEWED) {
							LogUtil.d(TAG, "hava items been shared without view!");
							compaireResult = HAVA_NEW_SHARE;
						}
					}
				}
			}
			

			handler.sendEmptyMessage(compaireResult);
			
			handler.postDelayed(scanTask, SCAN_LIFT_CYCLE);
		}
	};
	
	private Runnable scanTask = new Runnable() {
		@Override
		public void run() {
			new Thread() {
				@Override
				public void run() {
					scanShareChange();
					if(!scanTaskStoped) {
						handler.sendEmptyMessage(COMPIRE_SCAN_RESULT);
					}
				}
			}.start();
			
		}

		private void scanShareChange() {
			LogUtil.d(TAG, "begin scan share items!");
			list.clear();
			int pageIndex = -1;
			try {
				int result = -1;
				do {
					pageIndex++;
					result = loadAllShareData(pageIndex);
					LogUtil.d(TAG, "get share items "+pageIndex+" page!");
				} while(result != RESULT_GET_FINISHED);
			} catch (ClientException e) {
				LogUtil.e(TAG, "code: "+e.getCode()+",msg: "+e.getMessage());
			}
		}
		
		/**
		 * @param pageIndex 0,1,2,3....
		 * @return false if not complete load all
		 * @throws ClientException
		 */
		public int loadAllShareData(int pageIndex) throws ClientException {
			if(pageIndex < 0) {
				return RESULT_ERROR_INDEX;
			}
			
			ShareResourceV2 shareResponse = getShareService().getSharedResourceToMe(
					pageIndex, SHARE_PAGE_SIZE, null);
			List<INodeShareV2> shareList = null;
			if(shareResponse != null) {
				shareList = shareResponse.getContents();
				list.addAll(shareList);
			}
			
			if(shareList!= null && shareList.size() < SHARE_PAGE_SIZE) {
				return RESULT_GET_FINISHED;
			} else {
				return RESULT_NOT_FINISHED;
			}
		}
	};
}
